package xin.core.jwt;

import xin.core.AppConstant;
import xin.core.exception.AccountResetException;
import xin.lms.model.Jwtlog;
import xin.lms.repository.JwtlogRepository;
import xin.common.date.LocalDateConverter;
import xin.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;
import xin.pms.model.User;
import xin.pms.service.UserService;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <pre>
 * Jwt Filter 继承 OncePerRequestFilter
 * </pre>
 *
 * @author lixin
 * @since 2017/11/23 9:50
 */
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUserDetailsService userDetailsService;

    @Autowired
    private JwtTokenService jwtTokenUtil;

    @Autowired
    private JwtlogRepository jwtlogRepository;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        final String requestHeader = request.getHeader(AppConstant.JWT_HEADER);

        String username = null;
        String authToken = null;
        String jwtId = null;

        if (requestHeader != null && requestHeader.startsWith("Bearer ")) {
            authToken = requestHeader.substring(7);
            try {
                username = jwtTokenUtil.getUsernameFromToken(authToken);
                jwtId  = jwtTokenUtil.getJwtId(authToken);
            } catch (IllegalArgumentException e) {
                log.error("an error occured during getting username from token", e);
            }
        }

        if (username != null) {
            User user = userService.findByUserName(username);

            /**
             * 判断令牌有效性
             */
            if(StringUtils.isNotBlank(jwtId)){
                Jwtlog jwtlog = jwtlogRepository.findOne(jwtId);
                if(jwtlog == null ){
                    throw new BadCredentialsException("用户名或密码，请重新登录");
                }
                if(Jwtlog.TokenStatus.EXPIRED.getValue() == jwtlog.getTokenStatus().intValue()
                        || Jwtlog.TokenStatus.EXIT.getValue() == jwtlog.getTokenStatus().intValue()
                        || jwtTokenUtil.isTokenExpired(authToken)){
                    throw new AccountExpiredException("登录已过期，请重新登录");
                }
                if(jwtTokenUtil.isCreatedBeforeLastPasswordReset(jwtTokenUtil.getIssuedAtDateFromToken(authToken),
                        user.getLastPasswordResetDate())) {
                    throw new AccountResetException("密码已重置，请重新登录");
                }
                if(!username.equals(user.getUserName())){
                    throw new BadCredentialsException("用户名或密码错误，请重新登录");
                }
            }

            if(SecurityContextHolder.getContext().getAuthentication() == null){
                UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }

        chain.doFilter(request, response);
    }
}